package com.farm.project.controller;

import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.service.ProjectGradationServiceInter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;

import com.farm.web.easyui.EasyUiTreeNode;
import com.farm.web.easyui.EasyUiTreeNodeHandle;
import com.farm.web.easyui.EasyUiUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：项目阶段控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/projectgradation")
@Controller
public class ProjectGradationController extends WebUtils {
	private final static Logger log = Logger.getLogger(ProjectGradationController.class);
	@Resource
	private ProjectGradationServiceInter projectGradationServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
		try {
			if (query.getQueryRule().size() == 0) {
				query.addRule(new DBRule("PARENTID", "NONE", "="));
			}
			query = EasyUiUtils.formatGridQuery(request, query);
			query.addRule(new DBRule("PSTATE", "2", "!="));
			DataResult result = projectGradationServiceImpl.createProjectgradationSimpleQuery(query).search();
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					if (row.get("ID").equals(row.get("UUID"))) {
						row.put("ISDEMO", "是");
					} else {
						row.put("ISDEMO", "否");
					}
				}
			});
			result.runDictionary("0:树型分类,1:阶段类型", "MODEL");
			result.runDictionary("1:可用,0:停用", "PSTATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/chooseQuery")
	@ResponseBody
	public Map<String, Object> chooseQuery(DataQuery query, HttpServletRequest request) {
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			query.addRule(new DBRule("PSTATE", "1", "="));
			query.addRule(new DBRule("MODEL", "1", "="));
			DataResult result = projectGradationServiceImpl.createGradationChooseQuery(query).search();
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					if (row.get("ID").equals(row.get("UUID"))) {
						row.put("ISDEMO", "是");
					} else {
						row.put("ISDEMO", "否");
					}
				}
			});
			result.runDictionary("0:树型分类,1:阶段类型", "MODEL");
			result.runDictionary("1:可用,0:停用", "PSTATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/queryReTaskType")
	@ResponseBody
	public Map<String, Object> queryReTaskType(DataQuery query, String gradationId, HttpServletRequest request) {
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			query.addRule(new DBRule("a.GRADATIONID", gradationId, "="));
			query.addDefaultSort(new DBSort("a.SORT", "ASC"));
			DataResult result = projectGradationServiceImpl.createReTaskTypeQuery(query, gradationId).search();
			result.runDictionary("1:可用,0:停用,2:刪除","PSTATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 加载树节点
	 */
	@RequestMapping("/gradationTree")
	@ResponseBody
	public Object gradationTree(String id) {
		try {
			List<EasyUiTreeNode> allnodes = null;
			if (id == null) {
				// 如果是未传入id，就是根节点，就构造一个虚拟的上级节点
				id = "NONE";
				List<EasyUiTreeNode> list = new ArrayList<>();
				EasyUiTreeNode nodes = new EasyUiTreeNode("NONE", "阶段分类", "open", "icon-administrative-docs");
				nodes.setChildren(EasyUiTreeNode.formatAsyncAjaxTree(
						EasyUiTreeNode.queryTreeNodeOne(id, "SORT", "PLOGS_PROJECT_GRADATION", "ID", "PARENTID", "NAME",
								"CTIME","and a.PSTATE='1'").getResultList(),
						EasyUiTreeNode.queryTreeNodeTow(id, "SORT", "PLOGS_PROJECT_GRADATION", "ID", "PARENTID", "NAME",
								"CTIME","and a.PSTATE='1'").getResultList(),
						"PARENTID", "ID", "NAME", "CTIME"));
				list.add(nodes);
				allnodes = list;
			} else {
				allnodes = EasyUiTreeNode.formatAsyncAjaxTree(
						EasyUiTreeNode.queryTreeNodeOne(id, "SORT", "PLOGS_PROJECT_GRADATION", "ID", "PARENTID", "NAME",
								"CTIME","and a.PSTATE='1'").getResultList(),
						EasyUiTreeNode.queryTreeNodeTow(id, "SORT", "PLOGS_PROJECT_GRADATION", "ID", "PARENTID", "NAME",
								"CTIME","and a.PSTATE='1'").getResultList(),
						"PARENTID", "ID", "NAME", "CTIME");
			}
			EasyUiUtils.runTreeNodeHandle(allnodes, new EasyUiTreeNodeHandle() {
				@Override
				public void handle(EasyUiTreeNode node) {
					ProjectGradation type = projectGradationServiceImpl.getProjectgradationEntity(node.getId());
					if (type != null && type.getModel().equals("1")) {
						node.setIconCls("icon-future-projects");
					}
				}
			});
			return allnodes;
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(ProjectGradation entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = projectGradationServiceImpl.editProjectgradationEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(ProjectGradation entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = projectGradationServiceImpl.insertProjectgradationEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				projectGradationServiceImpl.deleteProjectgradationEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/formatSort")
	@ResponseBody
	public Map<String, Object> formatSort(String ids, HttpSession session) {
		try {
			int n = 1;
			for (String id : parseIds(ids)) {
				projectGradationServiceImpl.editSort(id, n++, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/ProjectGradationResult");
	}

	/**
	 * 跳转树选择页面
	 *
	 * @return
	 */
	@RequestMapping("/treeNodeTreeView")
	public ModelAndView treeNodeTreeView() {
		return ViewMode.getInstance().returnModelAndView("project/ChooseProjectGradationTree");
	}

	/**
	 * 移动节点
	 *
	 * @return
	 */
	@RequestMapping("/moveTreeNodeSubmit")
	@ResponseBody
	public Map<String, Object> moveTreeNodeSubmit(String ids, String id, HttpSession session) {
		try {
			projectGradationServiceImpl.moveTreeNode(ids, id, getCurrentUser(session));
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 阶段得任务分类绑定页面
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/tasyTypes")
	public ModelAndView tasyTypes(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/ProjectGradationToTaskType");
	}

	@RequestMapping("/chooseWin")
	public ModelAndView chooseWin(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/ChooseProjectGradationWin");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids, String parentId) {
		try {
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", projectGradationServiceImpl.getProjectgradationEntity(ids))
						.returnModelAndView("project/ProjectGradationForm");
			}
			case (1): {// 新增
				ProjectGradation parent = null;
				if (StringUtils.isNotBlank(parentId)) {
					parent = projectGradationServiceImpl.getProjectgradationEntity(parentId);
				}
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parent", parent)
						.returnModelAndView("project/ProjectGradationForm");
			}
			case (2): {// 修改
				ProjectGradation type = projectGradationServiceImpl.getProjectgradationEntity(ids);
				ProjectGradation parent = null;
				if (StringUtils.isNotBlank(type.getParentid())) {
					parent = projectGradationServiceImpl.getProjectgradationEntity(type.getParentid());
				}
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parent", parent)
						.putAttr("entity", type).returnModelAndView("project/ProjectGradationForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("project/ProjectGradationForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e)
					.returnModelAndView("project/ProjectGradationForm");
		}
	}

	/**
	 * 绑定阶段到任务分类
	 * 
	 * @return
	 */
	@RequestMapping("/bindTaskType")
	@ResponseBody
	public Map<String, Object> bindTaskType(String tasktypeids, String gradationid, HttpSession session) {
		try {
			for (String tasktypeid : parseIds(tasktypeids)) {
				projectGradationServiceImpl.bindTaskType(tasktypeid, gradationid, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 绑定阶段到任务分类
	 * 
	 * @return
	 */
	@RequestMapping("/rebindTaskType")
	@ResponseBody
	public Map<String, Object> rebindTaskType(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				projectGradationServiceImpl.rebindTaskType(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}
}
